package com.demo.youxuanmall.controller.admin;

import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.controller.BaseController;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.OrderService;
import com.demo.youxuanmall.service.ProductService;
import com.demo.youxuanmall.service.StatisticsService;
import com.demo.youxuanmall.service.SystemSettingService;
import com.demo.youxuanmall.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/admin/statistics")
public class AdminStatisticsController extends BaseController {

    private final OrderService orderService;
    private final ProductService productService;
    private final UserService userService;
    private final StatisticsService statisticsService;

    public AdminStatisticsController(SystemSettingService systemSettingService,
                                   OrderService orderService,
                                   ProductService productService,
                                   UserService userService,
                                   StatisticsService statisticsService) {
        super(systemSettingService);
        this.orderService = orderService;
        this.productService = productService;
        this.userService = userService;
        this.statisticsService = statisticsService;
    }

    /**
     * 统计数据页面
     */
    @GetMapping("/dashboard")
    public String statisticsPage(HttpSession session, Model model) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return "redirect:/403";
        }
        
        // 默认统计最近30天的数据
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(30);
        
        String startDateStr = startDate.format(DateTimeFormatter.ISO_DATE);
        String endDateStr = endDate.format(DateTimeFormatter.ISO_DATE);
        
        model.addAttribute("startDate", startDateStr);
        model.addAttribute("endDate", endDateStr);
        
        return "admin/statistics/dashboard";
    }
    
    @GetMapping("/data")
    @ResponseBody
    public Result<Map<String, Object>> getStatisticsData(
            @RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate,
            HttpSession session) {
        
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        // 获取统计数据
        Map<String, Object> statisticsData = orderService.getStatisticsData(startDate, endDate);
        
        // 获取热门商品（使用statisticsService）
        List<Map<String, Object>> hotProducts = statisticsService.getHotProducts(10).getData();
        statisticsData.put("hotProducts", hotProducts);
        
        // 获取用户增长数据
        Map<String, Object> userGrowth = userService.getUserGrowthData(startDate, endDate);
        statisticsData.put("userGrowth", userGrowth);
        
        return Result.success(statisticsData);
    }
    
    /**
     * 获取概览数据
     */
    @GetMapping("/overview")
    @ResponseBody
    public Result<Map<String, Object>> getOverview(HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        return statisticsService.getOverviewStats();
    }
    
    /**
     * 获取销售趋势
     */
    @GetMapping("/sales-trend")
    @ResponseBody
    public Result<Map<String, Object>> getSalesTrend(
            @RequestParam(required = false, defaultValue = "7") Integer days,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        return statisticsService.getSalesTrend(days);
    }
    
    /**
     * 获取订单状态分布
     */
    @GetMapping("/order-status")
    @ResponseBody
    public Result<Map<String, Integer>> getOrderStatus(HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        return statisticsService.getOrderStatusDistribution();
    }
    
    /**
     * 获取分类销售占比
     */
    @GetMapping("/category-sales")
    @ResponseBody
    public Result<List<Map<String, Object>>> getCategorySales(HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        return statisticsService.getCategorySalesPercentage();
    }
    
    /**
     * 获取热门商品
     */
    @GetMapping("/hot-products")
    @ResponseBody
    public Result<List<Map<String, Object>>> getHotProducts(
            @RequestParam(required = false, defaultValue = "10") Integer limit,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        return statisticsService.getHotProducts(limit);
    }
    
    /**
     * 获取用户增长数据
     */
    @GetMapping("/user-growth")
    @ResponseBody
    public Result<Map<String, Object>> getUserGrowth(
            @RequestParam(required = false, defaultValue = "7") Integer days,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        return statisticsService.getUserGrowth(days);
    }
} 